#
#  Copyright 2008 Garth Williams
#
#  This file is part of CommandPost.
#
#  CommandPost is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  CommandPost is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with CommandPost.  If not, see <http://www.gnu.org/licenses/>.
#

class PagesController < ApplicationController
  # GET /pages
  # GET /pages.xml
  def index
    @pages = Page.find(:all, :order => :name)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @pages }
    end
  end

  # GET /pages/1
  # GET /pages/1.xml
  def show
    name = params[:name]
    @page = Page.find_by_name(name)
    if @page == nil
      @page = Page.new(:name => name, :title => name,
        :body => 'This page does not yet exist.  PageEditors can click _edit_ to create this page.')
    end

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @page }
    end
  end

  # GET /pages/1/edit
  def edit
    name = params[:name]
    @page = Page.find_by_name(name)
    if @page == nil
      @page = Page.new(:name => name, :title => name)
    end
  end

  # PUT /pages/1
  # PUT /pages/1.xml
  def update
    name = params[:name]
    @page = Page.find_by_name(name)
    if @page == nil
      @page = Page.new(:name => name)
    end
    @page.created_by_user_id = session[:user_id]

    respond_to do |format|
      if @page.update_attributes(params[:page])
        flash[:notice] = 'Page was successfully saved.'
        format.html { redirect_to(:action => 'show', :name => name) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @page.errors, :status => :unprocessable_entity }
      end
    end
  end
end
